<?php
namespace App\Logic;

class AuthLogic
{
    public $m;
    public function __construct()
    {
        $this->m = M('admin');
    }

	//登录
	public function login($user, $pwd)
	{
		$info = M('admin')->where(array('user'=>$user))->find();
		if(!$info) {
			json(0, '无此账号信息');
		}
		if($info['st'] == 0){
			json(0, '帐号已被禁用');
		}
		if($info['pwd'] != md5($pwd)){
			json(0, '密码错误');
		}

		return $info['id'];
	}


	//获取并保存token
    public function createToken($id, $username)
    {
        //生成token
        $salt = C('SYNC_LOGIN_KEY');
        $overtime = C('TOKEN_OVER_TIME');
        $token = md5($id.$username.$salt.date('Y-m-d'));

        $where = array(
            'token'     =>  $token,
            'admin_id' =>  $id,
        );
        $rs = M('token')->where($where)->find();
        if($rs) {
            //更新token时间
            $rs = M('token')->where($where)->setField('exp_ts', time() + $overtime);
        }else{
            $where['exp_ts'] = time() + $overtime;
            //添加token
            $rs = M('token')->where($where)->add($where);
        }
        if($rs === false) json(0, '添加token失败');
        return $token;
    }

    //验证token
    public function checkToken($token)
    {
        $where = array(
            'token'     =>  $token,
        );
        $rs = M('token')->where($where)->find();
        if(!$rs) {
            json(0, '不存在此token');
        }
        if($rs['exp_ts'] - time() < 0) {
            json(0, 'token已经失效');
        }
        
        return $rs['admin_id'];
    }

    //获取可用菜单
    public function getMenuRouter($admin)
    {
        $role = $admin['role'];
        $menu = include(APP_PATH .'Common/Conf/menu.php');
        $group = M('role')->where(array('role' => $role))->find();
        $pri = $group['pri'] ? json_decode($group['pri'], true) : array();

        //从树中提取所有路由
        $router = tree_to_array($menu, 'name');

        //剔除树中不是菜单的节点,并标记节点层级
        foreach($menu as $k => $m) {
            $menu[$k]['lv'] = 1;
            if($m['type'] != 'menu') unset($menu[$k]);
            if($m['subs']) {
                foreach($m['subs'] as $t => $m2) {
                    $menu[$k]['subs'][$t]['lv'] = 2;
                    if($m2['type'] != 'menu') unset($menu[$k]['subs'][$t]);
                    if($m2['subs']) {
                        foreach($m2['subs'] as $j => $m3) {
                            $menu[$k]['subs'][$t]['subs'][$j]['lv'] = 3;
                            if($m3['type'] != 'menu') unset($menu[$k]['subs'][$t]['subs'][$j]);
                        }
                    }
                }
            }
        }

        if($role == 'admin') {
            return array('router' => $router, 'menu' => $menu);   //超管可用所以路由和菜单
        }

        //去除无权限的菜单
        foreach($menu as $k => $lv1) {
            if(!$lv1['subs']) {
                if(!in_array($lv1['name'], $pri)) {
                    unset($menu[$k]);
                }
            }else{
                foreach($lv1['subs'] as $t => $lv2) {
                    if(!$lv2['subs']) {
                        if(!in_array($lv2['name'], $pri)) {
                            unset($menu[$k]['subs'][$t]);
                        }
                    }else{
                        foreach($lv2['subs'] as $j => $lv3) {
                            if(!in_array($lv3['name'], $pri)) {
                                unset($menu[$k]['subs'][$t]['subs'][$j]);
                            }
                        }
                    }
                }
            }
        }


        //去除空2级菜单
        foreach($menu as $k => $lv1) {
            if($lv1['subs']) {
                foreach($lv1['subs'] as $t => $lv2) {
                    if($lv2['subs'] === array())  unset($menu[$k]['subs'][$t]);
                }
            }
        }

        //去除空一级菜单
        foreach($menu as $k => $lv1) {
            if($lv1['subs'] === array()) unset($menu[$k]);
        }

        //三级菜单重排key,否则丢给前端的有时是数组有时是对象
        $menu = array_values($menu);
        foreach($menu as &$lv1) {
            $lv1['subs'] = array_values($lv1['subs']);
            foreach($lv1['subs'] as &$lv2) {
                $lv2['subs'] = array_values($lv2['subs']);
            }
        }

        return array('router' => $pri, 'menu' => $menu);
    }

    /**
     * 根据admin_id判断是否有接口权限
     */
    public function checkApi($admin_id, $api)
    {
        $admin = M('admin')->find($admin_id);
        $role = $admin['role'];
        define('ROLE', $role);
        if($role == 'admin') return true;

		//免验证接口
		$ignore = ['/admin/get', '/admin/edit', '/index/upload'];
		if(in_array($api, $ignore)) return true;

        $menu = include(APP_PATH .'Common/Conf/menu.php');
        $group = M('role')->where(array('role'=>$role))->find();
        $pri = $group['pri'] ? json_decode($group['pri'], true) : array();  //可用接口

        //从树中提取所以api
        $menu = tree_to_array($menu);
        //转成name=>api映射数组
        $data = array_to_map($menu, 'name', 'api');
        //检测api是否有权限
        foreach ($data as $name => $item) {
            if(!in_array($name, $pri)) continue;    //路由无权限
            $apis = explode(',', str_replace(' ', '', $item));
            if(in_array($api, $apis)) return true;  //检测通过
            //处理带*号的接口权限，例如/wenku/*表示wenku下的所有接口可用
            foreach($apis as $a) {
                if(strpos($a, '*') !== false) {
                    $arr1 = explode('/', $a);
                    $arr2 = explode('/', $api);
                    if($arr1[1] == $arr2[1]) {
                        return true;
                    }
                }
            }

        }
		return false;
    }
}